//
//  HMUserAccountViewModel.swift
//  MicroBlog
//
//  Created by Apple on 16/9/22.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
//封装授权页面的网络请求->对应视图是HMOauthViewController
class HMUserAccountViewModel: NSObject {
    //判断是否登录
    var isLogin:Bool {
        return accessToken != nil
    }
    // 用户模型对象全局化
    static let sharedUserAccountViewModel: HMUserAccountViewModel = HMUserAccountViewModel()
    //用户归档用户对象
    var userAccount: HMUserAccount? {
        //从沙盒路径获取
        return HMUserAccount.loadUserAccount()
    }
    //判断accessTOken是否过期
    var accessToken: String? {
        //1.获取HMUserAccount里的accessToken
        let token = userAccount?.access_token
        //2.获取过期时间对象
        let expiresDate = userAccount?.expiresDate
        //3.如果token存在,判断其是否过期
        if let t = token {
            //过期时间大于当前时间
            if expiresDate?.compare(Date()) == .orderedDescending {
                return t
            } else {
                return nil
            }
        } else {
            return nil
        }
    }
    //通过code获取accesstoken
    func requestAccessToken(code: String, callBack: @escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
            if error != nil {
                print("网络请求异常: \(error)")
                callBack(false)
                return
            }
            //请求成功
            guard let dic = response as? [String: Any] else {
                return
            }
            //代码执行到此表示字典格式没有问题
            let userAccount = HMUserAccount(dic: dic)
            self.requestUserInfo(userAccount: userAccount, callBack: callBack)
        }
    }
    //通过accessToken和用户id获取用户信息
    private func requestUserInfo(userAccount: HMUserAccount, callBack: @escaping (Bool)->()) {
        HMNetworkTools.sharedTools.requestUserInfo(accessToken: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
            if error != nil {
                print("网络请求异常: \(error)")
                callBack(false)
                return
            }
            
            guard let dic = response as? [String: Any] else {
                //不是需要的字典
                callBack(false)
                return
            }
            
            let name = dic["name"]
            let avatar_hd = dic["avatar_hd"]
            
            userAccount.name = name as? String
            userAccount.avatar_hd = avatar_hd as? String
            //代码执行到此,登录成功,保存用户对象
            userAccount.saveUserInfo()
            callBack(true)
        }
    }

}
